import 'package:equatable/equatable.dart';

/// 单聊模型
/// 表示两个用户之间的私人聊天
class SingleChatModel extends Equatable {
  /// 聊天ID
  final String id;

  /// 参与聊天的用户ID列表（只有两个用户）
  final List<String> userIds;

  /// 聊天创建时间
  final DateTime createTime;

  /// 最后一条消息的时间
  final DateTime? lastMessageTime;

  /// 最后一条消息内容
  final String? lastMessage;

  /// 最后一条消息的发送者ID
  final String? lastMessageSenderId;

  /// 构造函数
  const SingleChatModel({
    required this.id,
    required this.userIds,
    required this.createTime,
    this.lastMessageTime,
    this.lastMessage,
    this.lastMessageSenderId,
  });

  /// 从JSON创建实例
  factory SingleChatModel.fromJson(Map<String, dynamic> json) {
    return SingleChatModel(
      id: json['id'] as String,
      userIds: List<String>.from(json['userIds'] as List),
      createTime: DateTime.parse(json['createTime'] as String),
      lastMessageTime:
          json['lastMessageTime'] != null
              ? DateTime.parse(json['lastMessageTime'] as String)
              : null,
      lastMessage: json['lastMessage'] as String?,
      lastMessageSenderId: json['lastMessageSenderId'] as String?,
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userIds': userIds,
      'createTime': createTime.toIso8601String(),
      'lastMessageTime': lastMessageTime?.toIso8601String(),
      'lastMessage': lastMessage,
      'lastMessageSenderId': lastMessageSenderId,
    };
  }

  /// 复制并修改属性
  SingleChatModel copyWith({
    String? id,
    List<String>? userIds,
    DateTime? createTime,
    DateTime? lastMessageTime,
    String? lastMessage,
    String? lastMessageSenderId,
  }) {
    return SingleChatModel(
      id: id ?? this.id,
      userIds: userIds ?? this.userIds,
      createTime: createTime ?? this.createTime,
      lastMessageTime: lastMessageTime ?? this.lastMessageTime,
      lastMessage: lastMessage ?? this.lastMessage,
      lastMessageSenderId: lastMessageSenderId ?? this.lastMessageSenderId,
    );
  }

  /// 获取聊天中的另一个用户ID
  String? getOtherUserId(String currentUserId) {
    if (userIds.length != 2) return null;
    return userIds.firstWhere((id) => id != currentUserId, orElse: () => '');
  }

  /// 检查用户是否参与此聊天
  bool isUserInChat(String userId) {
    return userIds.contains(userId);
  }

  /// 验证模型数据
  bool get isValid {
    return id.isNotEmpty &&
        userIds.length == 2 &&
        userIds.every((id) => id.isNotEmpty);
  }

  @override
  String toString() {
    return 'SingleChatModel(id: $id, userIds: $userIds, createTime: $createTime, lastMessageTime: $lastMessageTime, lastMessage: $lastMessage, lastMessageSenderId: $lastMessageSenderId)';
  }

  @override
  List<Object?> get props => [
    id,
    userIds,
    createTime,
    lastMessageTime,
    lastMessage,
    lastMessageSenderId,
  ];
}
